package org.yhx.learning.verticle.eventbus;/*
 * Copyright (C), 2024, bigmoon
 * FileName:
 * Author:   bigmoon
 * Date:     2024/9/5 11:27
 * Description: //模块目的、功能描述
 * History: //修改记录
 * &lt;author&gt;      &lt;time&gt;      &lt;version&gt;    &lt;desc&gt;
 * 修改人姓名             修改时间            版本号                  描述
 */

import io.vertx.core.AbstractVerticle;
import io.vertx.core.eventbus.EventBus;
import io.vertx.core.json.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 记录温度数据，然后计算平均值
 */
public class SensorDataVerticle extends AbstractVerticle {

    private static final Logger LOGGER = LoggerFactory.getLogger(SensorDataVerticle.class);

    List<Double> temps=new ArrayList<>();

    @Override
    public void start() throws Exception {
        EventBus eventBus = vertx.eventBus();
        this.logDate(eventBus);
        this.reply(eventBus);
    }

    private void logDate(EventBus eventBus){

        eventBus.<JsonObject>consumer("sensor.updates",(msg)->{

            LOGGER.info("消费 sensor.updates。 {}",msg.body().encode());
            temps.add(msg.body().getDouble("temp"));
        });
    }

    private void reply(EventBus eventBus){

        eventBus.consumer("sensor.average",(msg)->{
            Double collect = this.temps.stream().collect(Collectors.averagingDouble(Double::doubleValue));
            msg.reply(collect);
            LOGGER.info("回复完毕");
        });
    }
}
